<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://code.jquery.com/jquery-latest.min.js"></script>
  <title>Document</title>
  <style>
    #tree ul {
  list-style-type: none;
}

#tree li {
  margin: 5px 0 0 15px;
}

#tree span {
  cursor: pointer;
}
  </style>
</head>
<body>
  <div id="tree">
    <ul>
      <li>
        <span>节点1</span>
        <ul>
          <li><span>节点1.1</span></li>
          <li><span>节点1.2</span></li>
        </ul>
      </li>
      <li>
        <span>节点2</span>
        <ul>
          <li><span>节点2.1</span></li>
          <li>
            <span>节点2.2</span>
            <ul>
              <li><span>节点2.2.1</span></li>
              <li><span>节点2.2.2</span></li>
            </ul>
          </li>
        </ul>
      </li>
    </ul>
  </div>
</body>
<script>
   $(document).ready(function() {
  // 添加节点的点击事件
  $("#tree span").click(function(event) {
    event.stopPropagation(); // 阻止事件冒泡

    var $this = $(this);
    if ($this.next().length) { // 如果有子节点
      $this.next().toggle(200); // 显示或隐藏子节点
      $this.toggleClass("collapsed expanded"); // 切换样式类
    }
  });

  // 初始状态下隐藏所有子节点
  $("#tree li ul").hide();
  
  // 给根节点添加样式类
  $("#tree > ul > li > span").addClass("root");
});
</script>
</html>